let canvas = document.querySelector("#canvas");
let decreaseBtn = document.querySelector("#decrease");
let sizeEL = document.querySelector("#size");
let increaseBtn = document.querySelector("#increase");
let colorEl = document.querySelector("#color");
let clearEl = document.querySelector("#clear");
// let clearBtn = document.querySelector("#clear");

let ctx = canvas.getContext("2d");

let size = 10;
let isPressed = false;
let color = "black";
let x, y;

canvas.addEventListener("mousedown", (e) => {
	isPressed = true;
	x = e.offsetX;
	x = e.offsetY;
});

canvas.addEventListener("mouseup", (e) => {
	isPressed = false;
	x = undefined;
	y = undefined;
});

canvas.addEventListener("mousemove", (e) => {
	if (isPressed) {
		let x2 = e.offsetX;
		let y2 = e.offsetY;
		drawCircle(x2, y2);
		drawLine(x, y, x2, y2);

		x = x2;
		y = y2;
	}
});

function drawCircle(x, y) {
	ctx.beginPath();
	ctx.arc(x, y, size, 0, Math.PI * 2);
	ctx.fillStyle = color;
	ctx.fill();
}

function drawLine(x1, y1, x2, y2) {
	ctx.beginPath();
	ctx.moveTo(x1, y1);
	ctx.lineTo(x2, y2);
	ctx.strokeStyle = color;
	ctx.lineWidth = size * 2;
	ctx.stroke();
}

function updateSizeOnScreen() {
	sizeEL.innerText = size;
}

increaseBtn.addEventListener("click", () => {
	size += 5;

	if (size > 50) {
		size = 50;
	}

	updateSizeOnScreen();
});

decreaseBtn.addEventListener("click", () => {
	size -= 5;

	if (size < 5) {
		size = 5;
	}

	updateSizeOnScreen();
});

colorEl.addEventListener("change", (e) => (color = e.target.value));

clearEl.addEventListener("click", () =>
	ctx.clearRect(0, 0, canvas.width, canvas.height)
);
